package com.pro.ydl.service;

//import package
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import com.pro.ydl.MainHomeActivity;
import com.pro.ydl.R;
import com.pro.ydl.TestActivity;

import YDLControl.Control;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.Service;  
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;  
import android.content.IntentFilter;
import android.content.SharedPreferences.Editor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.IBinder;  
import android.os.Message;
import android.text.format.Time;
import android.util.Log;
import android.widget.Toast;

/*MyService explain*/
/*MyService extends service class and is a service application*/
/*MyService function as follows*/
/*1:check and get updating data from shaking phone always*/
/*2:listen system time for update status line data because of week changed to Monday*/
/*3:if running data of week is changed,then notify to the status line*/
public class MainService extends Service implements SensorEventListener{
	private static final String Tag = "MainService";
	
	/*shake phone times*/
	private double dPhoneShakeTimes=0;
	private Control control = null;
	private String sUserId =null;
	private static final int TIMEOUT_UPDATABASE_CHECK = 2;
	private static final int TIMEOUT_INSERTDATABASE_RESULT = 3;
	private static final int TIMEOUT_UPDATABASE_CHECK_RESULT = 4;
	private final Handler handler = new Handler()
	{
		@Override
		 public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			/*check shake phone count*/
			switch(msg.what)
			{
				//上传数据库timeout消息
				case TIMEOUT_UPDATABASE_CHECK:
				{
					if(! sUserId.equals("0"))
					{
					UpdateToBaseHandle();
					//Toast.makeText(MainService.this,"数据库上传web的时间到消息", Toast.LENGTH_SHORT).show();
					}
				}
				break;
				//插入step到数据库的消息
				case TIMEOUT_INSERTDATABASE_RESULT:
				{
					if(0 == msg.arg1)
					{
						//插入失败
						//Toast.makeText(MainService.this,"0或者30秒插入数据失败", Toast.LENGTH_SHORT).show();
					}
					else
					{
						//插入成功
						//Toast.makeText(MainService.this,"0或者30秒插入数据成功", Toast.LENGTH_SHORT).show();
					}
					
				}
				break;
				//数据库上传的结果返回
				case TIMEOUT_UPDATABASE_CHECK_RESULT:
				{
					if(-1 == msg.arg1)
					{
						//更新上传失败
					}
					else
					{
						//更新上传成功
					}
					//Toast.makeText(MainService.this,"更新成功或者失败", Toast.LENGTH_SHORT).show();
				}
				break;
			}
			
		}
	};
	SensorManager sensormanagerMainService;
	Sensor accsensorMainServiceSensor;
	float []dSensorAccelerateValue;
	float dWeekRunningSum;
	NotificationManager NotiManager=null;
	
	IntentFilter intentfilterMainServiceSysTime = null;
	BroadcastReceiver broadcastreceiverMainServiceSysTime = null;
	
	public void MainServiceSensorSectionInitial()
	{

		sensormanagerMainService = null;
		accsensorMainServiceSensor = null;
		dSensorAccelerateValue = new float[]{0,0,0};
		dWeekRunningSum = 0;
		sensormanagerMainService = (SensorManager)getSystemService(SENSOR_SERVICE);
		accsensorMainServiceSensor = sensormanagerMainService.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		if(null == sensormanagerMainService || null == accsensorMainServiceSensor)
		{
			Toast.makeText(MainService.this,"sensor get failure", Toast.LENGTH_SHORT).show();
		}	
		sensormanagerMainService.registerListener(this, accsensorMainServiceSensor,SensorManager.SENSOR_DELAY_NORMAL);
	}
//	public void MainServiceSysTimeListenerSectionInitial()
//	{
//		IntentFilter MainServiceIntentFilter = new IntentFilter();
//		MainServiceIntentFilter.addAction(Intent.ACTION_TIME_TICK);
//		MainServiceIntentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
//		//create system time listener,if it is a new day,then clear dMainServiceNewDayRunningSum
//		BroadcastReceiver MainServiceBroadcastReceiver = new BroadcastReceiver() 
//		{
//
//			@Override
//			public void onReceive(Context context, Intent intent) {
//				// TODO Auto-generated method stub
//				String action = intent.getAction();
//
//	            if (action.equals(Intent.ACTION_TIME_TICK) || action.equals(Intent.ACTION_TIMEZONE_CHANGED)) 
//	            {
//
//	            }
//				
//			}
//			
//		};
//		this.registerReceiver(MainServiceBroadcastReceiver, MainServiceIntentFilter, null, null);
//	}

	@Override
	public void onCreate()
	{
		Log.e(Tag, "MainService onCreate");
		super.onCreate();

		control = new Control();
		if(this.getSharedPreferences("YDL",Context.MODE_PRIVATE).getBoolean("bCurrentRegisterSts",false))
		{
			sUserId = this.getSharedPreferences("YDL",Context.MODE_PRIVATE).getString("sUserID","0");
		}
		else
		{
			sUserId = "0";
		}

		//30分钟的上传timeout
		UpdateBaseTimeInitial();
		//1秒的实时timeout检测
		CheckShakePhoneTimeInitial();
		//sensor initial
		MainServiceSensorSectionInitial();
		//MainServiceSysTimeListenerSectionInitial();
		NotiManager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		
	}
	public void InsertStepDataToBase(final double step)
	{
		new Thread()
		{
			@Override
			public void run()
			{

				//插入数据库step数据
				Date dateCurrentTime = new Date(System.currentTimeMillis());
				boolean ret = false;
			    Message msg = new Message();
			    msg.what = TIMEOUT_INSERTDATABASE_RESULT;
			    //调用接口
			    ret = control.insertStepsSingle(MainService.this,Integer.parseInt(sUserId),(int)step,dateCurrentTime);
			    
			    if(false == ret)
		    	{
				    msg.arg1 = 0;
		    	}
		    	else
		    	{
		    		msg.arg1 = 1;
		    	}
				handler.sendMessage(msg);
			}
		}.start();
		
	}
	public void UpdateToBaseHandle()
	{
		new Thread()
		{
			@Override
			public void run()
			{
				//打包上传数据到web
				int ret = -1;
				//ret = control.uploadDataToServer(sUserId,control.wrapUploadData(sUserId,MainService.this),"1");
			    Message msg = new Message();
			    msg.what = TIMEOUT_UPDATABASE_CHECK_RESULT;
			    msg.arg1 = ret;
				handler.sendMessage(msg);
			}
		}.start();
	}
	public void UpdateBaseTimeInitial()
	{
		new Thread()
		{
			@Override
			public void run()
			{
				while(true)
				{
					try {
						Thread.sleep(1000*50);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				    Message msg = new Message();
				    msg.what = TIMEOUT_UPDATABASE_CHECK;
					handler.sendMessage(msg);
				}
			}
		}.start();
	}
	public void CheckShakePhoneTimeInitial()
	{
		new Thread()
		{
			@Override
			public void run()
			{
				while(true)
				{
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
	            	//判断当天的秒数为0或者是30秒
	            	Time time = new Time("GMT+8");    
	                time.setToNow();
	                int hour = time.hour;
	                int mins = time.minute;
	                int second = time.second;
	                if(0 == second || 29 == second)
	                {
	                	//启动thread完成插入数据库
	                	InsertStepDataToBase(dPhoneShakeTimes);
	                	dPhoneShakeTimes = 0;
	                }
				}
			}
		}.start();
	}
	@Override
	public void onStart(Intent intent, int startId)
	{
		Log.e(Tag, "MainService onStart");
		super.onStart(intent, startId);

	}
	
	@Override
	public void onDestroy()
	{
		Log.e(Tag, "MainService onDestroy");
		super.onDestroy();
		NotiManager.cancel(0);
		sensormanagerMainService.unregisterListener(this);
	}
	
	//notify to status line
	public void MainServiceNotificationSts() 
	{	

		NotiManager.cancelAll();
		
		Notification Noti = new Notification();
		//set icon
		Noti.icon=R.drawable.logo;
		Noti.defaults=Notification.DEFAULT_SOUND;
		Noti.tickerText = "YDL Notification";
		//set show notification time
		Noti.when = System.currentTimeMillis(); 
		//set flag
		Noti.flags = Notification.FLAG_ONGOING_EVENT;

		
		Intent intent = new Intent(this, MainHomeActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
		//set low pull_list
	    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 
	    Noti.setLatestEventInfo(this,"运动令跑步数据","跑动距离"+dWeekRunningSum+"米", pendingIntent);  

	    NotiManager.notify(0,Noti);
	}
	public void MainServiceClearNotifications()
	{
		
	}
	//compare whether current time is 00:00:00(a new day) or not
	public boolean SportsMyServiceCheckNewDay()
	{
		boolean ret = false;
		SimpleDateFormat SDFHour = new SimpleDateFormat("HH",Locale.CHINA);
		SimpleDateFormat SDFMin = new SimpleDateFormat("mm",Locale.CHINA);
		SimpleDateFormat SDFSec = new SimpleDateFormat("ss",Locale.CHINA);
		String Hour= SDFHour.format(new Date());
		String Min= SDFMin.format(new Date());
		String Sec= SDFSec.format(new Date());
		if((Hour.equalsIgnoreCase("00")) && (Min.equalsIgnoreCase("00")) && (Sec.equalsIgnoreCase("00")))
		{
			ret = true;
		}
		return(ret);
	}
	
	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSensorChanged(SensorEvent arg0) 
	{
		// TODO Auto-generated method stub
		int sensorType = arg0.sensor.getType();
		
		if(sensorType == Sensor.TYPE_ACCELEROMETER)
		{	
			dSensorAccelerateValue[0] = arg0.values[SensorManager.DATA_X];
			dSensorAccelerateValue[1] = arg0.values[SensorManager.DATA_Y];
			dSensorAccelerateValue[2] = arg0.values[SensorManager.DATA_Z];
			if(dSensorAccelerateValue[0] >15 || dSensorAccelerateValue[1] >15 || dSensorAccelerateValue[2] >15)
			{
				dWeekRunningSum += CompareMax(dSensorAccelerateValue[0],dSensorAccelerateValue[1],dSensorAccelerateValue[2]);
				MainServiceNotificationSts();
				//count number
				dPhoneShakeTimes++;
			}

		}
		
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	public float CompareMax(float a,float b,float c)
	{
		float ret = 0;
		if(a>b)
		{
			if(a>c)
			{
				ret = a;
			}
			else
			{
				ret = c;
			}
		}
		else
		{
			if(b>c)
			{
				ret = b;
			}
			else
			{
				ret = c;
			}
		}
		return (ret);
		
	}

}
